package me.fung.rem.component

import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.ExternalDragValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun TextInput(
    placeholder: String,
    onSubmit: (String) -> Unit,
    buttonContent: @Composable RowScope.() -> Unit,
    modifier: Modifier = Modifier,
    leadingIcon: @Composable (() -> Unit)? = null,
    initText: String = "",
    requestFocuses: Boolean = true,
    visualTransformation: VisualTransformation = VisualTransformation.None,

    ) {
    var value: String by remember { mutableStateOf(initText) }
    val focusRequester = remember { FocusRequester() }
    LaunchedEffect(Unit) {
        if (requestFocuses) focusRequester.requestFocus()
    }
    Surface(
        modifier = Modifier.height(IntrinsicSize.Min),
        shape = RoundedCornerShape(50),
    ) {
        Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
            TextField(
                value = value,
                onValueChange = { value = it },
                placeholder = {
                    Text(text = placeholder)
                },
                modifier = Modifier.focusRequester(focusRequester).onKeyEvent {
                    if (it.key == Key.Enter) {
                        onSubmit(value)
                        return@onKeyEvent true
                    }
                    false
                },
                visualTransformation = visualTransformation,
                singleLine = true,
                leadingIcon =leadingIcon,
            )
            Button(
                onClick = {
                    if (requestFocuses) focusRequester.requestFocus()
                    onSubmit(value)
                },
                modifier = Modifier.fillMaxHeight(),
                shape = RectangleShape,
                content = buttonContent,
            )
        }
    }

}
